import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:super_sliver_list/super_sliver_list.dart';

import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../bloc/SelectUsersCubit.dart';
import 'component/UserIconView.dart';
import 'component/cell/UserItemSelectView.dart';
import 'component/SearchView.dart';

class SelectUsersView extends StatefulWidget {

  final Widget? groupWidget;

  const SelectUsersView({ this.groupWidget, super.key});

  @override
  State<StatefulWidget> createState() => _SelectUsersState();
}

class _SelectUsersState extends State<SelectUsersView> {

  // late AutoScrollController _userScrollController;
  // late AutoScrollController _selectedUserScrollController;
  late ListController _userListScrollController;
  late ScrollController _userScrollController;
  late ListController _selectedUserListScrollController;
  late ScrollController _selectedUserScrollController;

  @override
  void initState() {
    // _userScrollController = AutoScrollController(
    //     viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
    //     axis: Axis.vertical);
    //
    // _selectedUserScrollController = AutoScrollController(
    //     viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
    //     axis: Axis.vertical);

    _userListScrollController = ListController();
    _userScrollController = ScrollController();
    _selectedUserListScrollController = ListController();
    _selectedUserScrollController = ScrollController();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var selectUsersCubit = context.watch<SelectUsersCubit>();
    var state = selectUsersCubit.state;
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
          child: SearchView<SelectUsersCubit>(
            prefix: state.selectedUsers.isNotEmpty ? _buildSelectedUserList(state) : null,
            searchHandler: _doSearch,
            param: selectUsersCubit,
          ),
        ),
        const SizedBox(
          height: 10,
        ),
        Expanded(child: Container(
          color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
          child: _buildBody(context, selectUsersCubit),
        )),
      ],
    );
  }

  Widget _buildBody(BuildContext context, SelectUsersCubit selectUsersCubit) {
    if (selectUsersCubit.state.search == '') {
      return _buildUserContainer(selectUsersCubit);
    } else {
      return _buildSearchResult(selectUsersCubit);
    }
  }

  Widget _buildUserContainer(SelectUsersCubit selectUsersCubit) {
    return Stack(
      children: [
        _buildUserList(selectUsersCubit),
        Positioned(
          right: 10,
          child: Center(
            child: Column(
                children: selectUsersCubit.state.letters
                    .asMap()
                    .map<int, Widget>((index, letter) => MapEntry(
                    index,
                    GestureDetector(
                      child: _buildLetter(letter),
                      onTap: () => _jumpToUser(selectUsersCubit.state.letters, selectUsersCubit.state.letterSizeMap, letter),
                    )))
                    .values
                    .toList()),
          ),
        )
      ],
    );
  }

  Widget _buildSearchResult(SelectUsersCubit selectUsersCubit) {
    List<ImUser> showUsers = selectUsersCubit.state.filterUsers;
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        return UserItemSelectView(user: showUsers.elementAt(index), isSelected: selectUsersCubit.state
            .existedUserIdSet.contains(showUsers.elementAt(index).userId),);
      },
      itemCount: showUsers.length,
    );
  }

  Widget _buildUserList(SelectUsersCubit selectUsersCubit) {
    List<ImUser> allUsers = selectUsersCubit.state.allUsers;
    var groupWidget = widget.groupWidget;
    // return CustomScrollView(
    //   slivers: [
    //     if (groupWidget != null)
    //       SliverToBoxAdapter(
    //         child: groupWidget,
    //       ),
    //     SliverList.builder(
    //       itemBuilder: (BuildContext context, int index) {
    //         var preUser = index > 0 ? allUsers.elementAt(index - 1) : null;
    //         var user = allUsers.elementAt(index);
    //         Set<String> existedUserIdSet = selectUsersCubit.state.existedUserIdSet;
    //         return AutoScrollTag(
    //             key: ValueKey(index),
    //             controller: _userScrollController,
    //             index: index,
    //             child: UserItemSelectView(user: user,
    //               preUser: preUser,
    //               selectedUserScrollController: _selectedUserScrollController,
    //               isSelected: existedUserIdSet.contains(user.userId),
    //             )
    //
    //         );
    //       },
    //       itemCount: allUsers.length,
    //     ),
    //   ],
    //   controller: _userScrollController,
    // );
    return SuperListView.builder(
      listController: _userListScrollController,
      controller: _userScrollController,
      scrollDirection: Axis.vertical,
      itemCount: allUsers.length,
      physics: const BouncingScrollPhysics(),
      // shrinkWrap: true,
      cacheExtent: 5,
      itemBuilder: (context, index) {
        var preUser = index > 0 ? allUsers.elementAt(index - 1) : null;
        var user = allUsers.elementAt(index);
        Set<String> existedUserIdSet = selectUsersCubit.state.existedUserIdSet;
        return UserItemSelectView(user: user,
          preUser: preUser,
          selectedUserListScrollController: _userListScrollController,
          selectedUserScrollController: _userScrollController,
          isSelected: existedUserIdSet.contains(user.userId),
        );
      },
      // separatorBuilder: (context, index) {
      //   return Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: ListSeparator(),);
      // },
    );
  }

  Widget _buildLetter(String letter) {
    return Container(
      width: 20,
      padding: const EdgeInsets.only(left: 5, right: 10, top: 2, bottom: 2),
      decoration: const ShapeDecoration(
        shape: CircleBorder(),
        color: Colors.black12, // 圆点的颜色
      ),
      child: Center(
        child: Text(
          letter,
          style: const TextStyle(
            color: Colors.black87,
          ),
        ),
      ),
    );
  }

  Widget _buildSelectedUserList(SelectUsersState state) {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _selectedUserListScrollController.jumpToItem(index: state.selectedUsers.length-1, scrollController:
      _userScrollController, alignment: 0);
    });
    return ConstrainedBox(
      constraints: const BoxConstraints(maxWidth: 33 * 7),
      child: Container(
        width: 30.0 * state.selectedUsers.length + 20.0,
        height: 40,
        margin: const EdgeInsets.only(right: 10),
        child: SuperListView.builder(
          listController: _selectedUserListScrollController,
          controller: _selectedUserScrollController,
          scrollDirection: Axis.horizontal,
          itemCount: state.selectedUsers.length,
          physics: const BouncingScrollPhysics(),
          // shrinkWrap: true,
          cacheExtent: 5,
          itemBuilder: (context, index) {
            return Container(
              margin: const EdgeInsets.only(left: 3, top: 3, bottom: 3),
              decoration: BoxDecoration(
                  border: Border.all(color: ImConstant.IM_MAIN_BACKGROUND_COLOR, width: 1),
                  borderRadius: const BorderRadius.all(Radius.circular(5))),
              child: GestureDetector(
                onTap: () async {
                  var uindex = state.allUsers.indexOf(state.selectedUsers[index]);
                  if (uindex >= 0) {
                    _userListScrollController.jumpToItem(index: uindex, scrollController: _userScrollController, alignment: 0);
                  }
                },
                child: UserIconView(user: state.selectedUsers[index], iconSize: 30,),
              ),
            );
          },
          // separatorBuilder: (context, index) {
          //   return Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: ListSeparator(),);
          // },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _userScrollController.dispose();
    _selectedUserScrollController.dispose();
    super.dispose();
  }

  /// 调整首字母处
  void _jumpToUser(List<String> letters, Map<String, int> letterSizeMap, String letter) async {
    var size = 0;
    print('Current letter0: $letter');
    for (var i = 0; i < letters.length; i++) {
      if (letters[i] == letter) {
        break;
      }
      size += letterSizeMap[letters[i]] ?? 0;
    }
    print('Current letter0: $letter, $size');
    _userListScrollController.jumpToItem(index: size, scrollController: _userScrollController, alignment: 0);
  }

  void _doSearch(dynamic? context1, String searchText) {
    if (context1 == null) return;
    var selectUsersCubit = context1 as SelectUsersCubit;
    selectUsersCubit.add(SelectUsersSearchEvent(searchText));
  }

}